package com.friend.chat.chat

import android.app.Activity
import android.content.Context
import android.graphics.BitmapFactory
import android.text.Editable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ImageSpan
import android.util.Log
import android.view.View
import android.view.View.OnFocusChangeListener
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.friend.chat.R
import com.friend.chat.base.BaseActivity
import com.friend.chat.databinding.ActivitySingleChatBinding
import com.friend.chat.db.ChatDatabase
import com.friend.chat.db.dao.MessageDao
import com.friend.chat.db.entity.MessageEntity
import com.friend.chat.media.pressAudio.MessageStreamBody
import com.friend.chat.media.video.SingleVideoActivity
import com.friend.chat.page.bean.FriendBean
import com.friend.chat.page.bean.UserBean
import com.friend.chat.utils.*
import com.friend.chat.websocket.ChatMessageBean
import com.friend.chat.websocket.WebSocketManager
import com.google.gson.Gson
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.runOnUiThread
import java.io.FileOutputStream
import java.util.*
import kotlin.collections.ArrayList

/**
 * 单聊
 */
class SingleChatActivity : BaseActivity<ActivitySingleChatBinding, SingleChatViewModel>() {
    private lateinit var fileOutputStream: FileOutputStream
    private lateinit var mUserBean: UserBean
    private lateinit var mFriendBean: FriendBean
    private lateinit var mAdapter: SingleChatAdapter
    private var mList = ArrayList<ChatMessageBean>()
    private var mUserId = ""
    private var mToUid = ""
    private var mUserHeader = ""
    private var mToHeader = ""
    private var mToNickName = ""
    private lateinit var mMessageDao: MessageDao
    private var mEmoSelected = false
    private var mCount = 0

    override fun yourViewModel(): SingleChatViewModel {
        return SingleChatViewModel()
    }

    override fun yourViewBing(): ActivitySingleChatBinding {
        return ActivitySingleChatBinding.inflate(layoutInflater)
    }

    override fun init() {
        fileOutputStream = FileOutputStream(application.cacheDir.toString() + "test1.png")
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        mCount = 0
        mUserBean = intent.getSerializableExtra("userBean") as UserBean
        mFriendBean = intent.getSerializableExtra("friendBean") as FriendBean
        mUserId = mUserBean.uid
        mUserHeader = mUserBean.header
        mToUid = mFriendBean.friendId
        mToNickName = mFriendBean.friendNickName
        mToHeader = mFriendBean.friendHeader
        mMessageDao = ChatDatabase.getDatabase(this).messageDao()
        mViewBinding.tvTitle.text = mToNickName
        initRecyclerView()
        mVModel.getUnReadChatList(getRoomId(mUserId, mToUid), mUserId)
    }

    private fun initRecyclerView() {
        //聊天内容recycleView
        val linearLayoutManager = object : LinearLayoutManager(this) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        linearLayoutManager.stackFromEnd = true
        mAdapter = SingleChatAdapter(this,mList, mUserBean, mFriendBean)
        mViewBinding.rvChatSingle.layoutManager = linearLayoutManager
        mViewBinding.rvChatSingle.adapter = mAdapter
        mViewBinding.srlSingle.setOnRefreshListener {
            getDataBaseMessages()
        }


        val gridLayoutManager = object : GridLayoutManager(this, 8) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        val emojiAdapter =
            object : BaseQuickAdapter<EmojiBean, BaseViewHolder>(R.layout.item_emoji) {
                override fun convert(holder: BaseViewHolder, item: EmojiBean) {
                    holder.setImageResource(R.id.iv_emoji, item.emojiRes)
                }
            }

        mViewBinding.rvEmoji.layoutManager = gridLayoutManager
        mViewBinding.rvEmoji.adapter = emojiAdapter
        val emojiList = EmojiUtil.getEmojiList()
        emojiAdapter.setList(emojiList)
        emojiAdapter.setOnItemClickListener { adapter, _, position ->
            val data = adapter.data[position] as EmojiBean
            val spannableString = SpannableString(data.emojiString);
            val imageSpan = ImageSpan(this, BitmapFactory.decodeResource(resources, data.emojiRes))
            spannableString.setSpan(
                imageSpan,
                0,
                data.emojiString.length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            mViewBinding.edtTextMsg.append(spannableString)
        }

    }

    override fun onNetListener() {
        super.onNetListener()
        mVModel.unReadListResponse.observe(this) { result ->
            val data = result.data
            Thread {
                data?.apply {
                    val dataList = ArrayList<ChatMessageBean>()
                    //插入本地数据库
                    if (data.isNotEmpty()) {
                        data.forEach {
                            try {
                                val messageEntity = MessageEntity()
                                messageEntity.userId = it.userId
                                messageEntity.toUid = it.toUid
                                messageEntity.type = it.type
                                messageEntity.roomType = it.type
                                messageEntity.message = it.message.toString()
                                messageEntity.dateTime = it.dateTime ?: "2022-12-24 18:15:00"
                                messageEntity.messageId = it.messageId ?: ""
                                messageEntity.roomId = it.roomId ?: ""
                                mMessageDao.insertMessage(messageEntity)
                            } catch (e: Exception) {
                                //insert不进去
                            }
                        }
                    }
                    //从本地数据库取出来
                    val saveListData =
                        mMessageDao.queryMessage(getRoomId(mUserId, mFriendBean.friendId), 0)
                    if (saveListData.isNotEmpty()) {
                        saveListData.reverse()

                        for (data in saveListData) {
                            Log.e("--->", data.toString())
                            dataList.add(
                                ChatMessageBean(
                                    data.userId,
                                    data.toUid,
                                    data.type,
                                    data.roomType,
                                    data.message,
                                    data.dateTime,
                                    data.messageId,
                                    getRoomId(mUserId, mFriendBean.friendId)
                                )
                            )
                        }
                    }
                    runOnUiThread {
                        mAdapter.setList(dataList)
                        if (mAdapter.data.size > 0) {
                            mViewBinding.rvChatSingle.smoothScrollToPosition(mAdapter.data.size - 1)
                        }
                        sendReadAck()
                    }
                }
            }.start()
        }

        mVModel.uploadPicResponse.observe(this) {
            val text: String = it.data ?: return@observe
            val messageId = UUID.randomUUID().toString()
            val dateTime = DateUtils.getTodayDate()
            val message = ChatMessageBean(
                mUserId,
                mToUid,
                type = CHAT_IMAGE,
                roomType = CHAT_ROOM_SINGLE,
                message = text,
                dateTime,
                messageId,
                getRoomId(mUserId, mToUid)
            )
            //数据库操作
            Thread {
                val messageEntity = MessageEntity()
                messageEntity.userId = mUserId
                messageEntity.toUid = mToUid
                messageEntity.type = CHAT_IMAGE
                messageEntity.roomType = CHAT_ROOM_SINGLE
                messageEntity.message = text
                messageEntity.dateTime = dateTime
                messageEntity.messageId = messageId
                messageEntity.roomId = getRoomId(mUserId, mToUid)
                mMessageDao.insertMessage(messageEntity)
            }.start()
            //发送
            WebSocketManager.instance.sendMessage(Gson().toJson(message))
            mAdapter.addData(message)
            mViewBinding.rvChatSingle.smoothScrollToPosition(mAdapter.data.size - 1)
        }
    }

    private fun getDataBaseMessages() {
        Thread {
            val dataList = ArrayList<ChatMessageBean>()
            dataList.clear()
            //从本地数据库取出来
            mCount = (mCount + 1) * 20
            val saveListData =
                mMessageDao.queryMessage(getRoomId(mUserId, mFriendBean.friendId), mCount)
            if (saveListData.isNotEmpty()) {
                saveListData.reverse()
                for (data in saveListData) {
                    Log.e("--->", data.toString())
                    dataList.add(
                        ChatMessageBean(
                            data.userId,
                            data.toUid,
                            data.type,
                            data.roomType,
                            data.message,
                            data.dateTime,
                            data.messageId,
                            getRoomId(mUserId, mFriendBean.friendId)
                        )
                    )
                }
            }
            runOnUiThread {
                mViewBinding.srlSingle.finishRefresh()
                Log.e("-->", "dataList.size==>" + dataList.size)
                Log.e("--->", "mCount==>" + mCount)
                if (dataList.size > 0) {
                    mAdapter.addData(0, dataList)
                    //  mViewBinding.rvChatSingle.smoothScrollToPosition(mAdapter.data.size - 1)
                } else {
                    mViewBinding.srlSingle.setEnableRefresh(false)
                }

            }

        }.start()
    }

    override fun setClick() {
        super.setClick()

        mViewBinding.ivBack.setOnClickListener {
            finish()
        }

        mViewBinding.btnSetModeVoice.setOnClickListener {
            //   AudioActivity.open(this, mFriendBean.friendId, true)
/*            val messageId = UUID.randomUUID().toString()
            val dateTime = DateUtils.getTodayDate()
           val chatMessageBean =  ChatMessageBean(
                mUserId,
                mToUid,
                CHAT_VOICE,
                roomType = CHAT_ROOM_SINGLE,
                message = "",
                dateTime,
                messageId,
                getRoomId(mUserId, mToUid)
            )
            val  testFile = File(cacheDir.path+"/test.png")
            if (testFile.exists()){
                testFile.delete()
            }
            try {
                val inputStream= assets.open("test.png")
                val fos = FileOutputStream(testFile)

                var buf = ByteArray(1024)
                var read =0;
                while (read!=-1){
                    read = inputStream.read(buf)
                    fos.write(buf,0,read)
                    Log.e("--->",read.toString())
                }
                fos.close()

                inputStream.close()

            } catch (e: Exception) {
            }
            sendFile(testFile,chatMessageBean)
          Glide.with(this).load(testFile).into(mViewBinding.ivBack)*/
            SingleVideoActivity.open(this, mToUid, true)

        }

        mViewBinding.ivEmojiNormal.setOnClickListener {
            mEmoSelected = !mEmoSelected
            mViewBinding.ivEmojiNormal.isSelected = mEmoSelected

            if (mEmoSelected) {
                hideKeyboard(this)
                mViewBinding.edtTextMsg.clearFocus()
                mViewBinding.llMore.visibility = View.GONE
                mViewBinding.flEmoji.visibility = View.VISIBLE
            } else {
                mViewBinding.flEmoji.visibility = View.GONE
                mViewBinding.llMore.visibility = View.GONE
                // showKeyboard(this,mViewBinding.edtTextMsg)
                mViewBinding.edtTextMsg.requestFocus()
                showKeyboard(this, mViewBinding.edtTextMsg)
            }
        }

        mViewBinding.btnSend.setOnClickListener {
            val text = mViewBinding.edtTextMsg.text.toString()
            val messageId = UUID.randomUUID().toString()
            val dateTime = DateUtils.getTodayDate()
            val message = ChatMessageBean(
                mUserId,
                mToUid,
                type = CHAT_TEXT,
                roomType = CHAT_ROOM_SINGLE,
                message = text,
                dateTime,
                messageId,
                getRoomId(mUserId, mToUid)
            )
            //数据库操作
            Thread {
                val messageEntity = MessageEntity()
                messageEntity.userId = mUserId
                messageEntity.toUid = mToUid
                messageEntity.type = CHAT_TEXT
                messageEntity.roomType = CHAT_ROOM_SINGLE
                messageEntity.message = text
                messageEntity.dateTime = dateTime
                messageEntity.messageId = messageId
                messageEntity.roomId = getRoomId(mUserId, mToUid)
                mMessageDao.insertMessage(messageEntity)
            }.start()
            //发送
            WebSocketManager.instance.sendMessage(Gson().toJson(message))
            mAdapter.addData(message)
            mViewBinding.rvChatSingle.smoothScrollToPosition(mAdapter.data.size - 1)
            mViewBinding.edtTextMsg.setText("")
        }

        mViewBinding.edtTextMsg.onFocusChangeListener =
            OnFocusChangeListener { v, hasFocus ->
                if (hasFocus) {
                    mEmoSelected = false
                    mViewBinding.ivEmojiNormal.isSelected = mEmoSelected
                    mViewBinding.flEmoji.visibility = View.GONE
                }
            }


        mViewBinding.edtTextMsg.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null && s.isNotEmpty()) {
                    mViewBinding.btnSend.visibility = View.VISIBLE
                    mViewBinding.btnMore.visibility = View.GONE

                } else {
                    mViewBinding.btnSend.visibility = View.GONE
                    mViewBinding.btnMore.visibility = View.VISIBLE

                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        mViewBinding.edtTextMsg.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                mViewBinding.llMore.visibility = View.GONE
                mViewBinding.flEmoji.visibility = View.GONE
            }
        }
        mViewBinding.btnMore.setOnClickListener {
            hideKeyboard(this)
            mViewBinding.edtTextMsg.clearFocus()
            mViewBinding.llMore.visibility = View.VISIBLE
            mViewBinding.flEmoji.visibility = View.GONE
        }

        mViewBinding.flEmojiDelete.setOnClickListener {
            val start = mViewBinding.edtTextMsg.text.toString()
            if (start.isEmpty()) {
                return@setOnClickListener
            }
            var i = start.lastIndexOf("[")
            if (i != -1) {
                var cs = start.subSequence(i, start.length)
                Log.e("--->", "setClick: $cs")
                if (cs.startsWith("[:")) {
                    mViewBinding.edtTextMsg.editableText.delete(i, start.length)
                    return@setOnClickListener
                }
            }
            mViewBinding.edtTextMsg.editableText.delete(start.length - 1, start.length)
        }

        //相册
        mViewBinding.flBGallery.setOnClickListener {
            PictureSelectorHelper().takeAndSelectPhoto1(this, 4) {
                mVModel.uploadImage(it)
            }
        }

        //拍照
        mViewBinding.flBPhoto.setOnClickListener {
            PictureSelectorHelper().takePhoto(this) {
                mVModel.uploadImage(it)
            }
        }

        //视频通话
        mViewBinding.flBVideo.setOnClickListener {

        }

        mViewBinding.rlRecycle.setOnClickListener {
            hideKeyboard(this)
            mViewBinding.edtTextMsg.clearFocus()
            mViewBinding.llMore.visibility = View.GONE
            mViewBinding.flEmoji.visibility = View.GONE
        }
    }

  inner  class SingleChatAdapter : BaseMultiItemQuickAdapter<ChatMessageBean, BaseViewHolder> {
        private var mUserBean: UserBean
        private var mFriendBean: FriendBean
        private var mActivity : Activity

        constructor(
            activity: Activity,
            data: MutableList<ChatMessageBean>?,
            userBean: UserBean,
            friendBean: FriendBean
        ) : super(data) {
            addItemType(CHAT_TEXT, R.layout.item_chat_text)
            addItemType(CHAT_IMAGE, R.layout.item_chat_image)
            mUserBean = userBean
            mFriendBean = friendBean
            mActivity = activity
        }

        override fun convert(holder: BaseViewHolder, item: ChatMessageBean) {
            holder.itemView.setOnClickListener {
               hideKeyboard(this@SingleChatActivity)
                mViewBinding.edtTextMsg.clearFocus()
                mViewBinding.llMore.visibility = View.GONE
                mViewBinding.flEmoji.visibility = View.GONE
            }
            when (holder.itemViewType) {
                //text
                CHAT_TEXT -> {
                    val dateTimeView = holder.getView<TextView>(R.id.tv_item_datetime)
                    val leftView = holder.getView<LinearLayout>(R.id.ll_item_text_left)
                    val rightView = holder.getView<LinearLayout>(R.id.ll_item_text_right)
                    val friendHeaderView = holder.getView<ImageView>(R.id.iv_item_text_friend)
                    val meHeaderView = holder.getView<ImageView>(R.id.iv_item_text_me)

                    if (holder.layoutPosition == 0) {
                        dateTimeView.visibility = View.VISIBLE

                    } else {
                        val dataFore = data[holder.layoutPosition - 1].dateTime
                        val before = DateUtils.dateToStamp2(dataFore)
                        val after = DateUtils.dateToStamp2(item.dateTime)

                        if ((after - before) > 1000 * 120) {
                            dateTimeView.visibility = View.VISIBLE
                        } else {
                            dateTimeView.visibility = View.GONE
                        }
                    }
                    dateTimeView.text = DateUtils.convertTimeToFormat(
                        DateUtils.dateToStamp2(item.dateTime),
                        item.dateTime
                    )
                    if (mUserBean.uid != item.userId) {
                        //左边的 -- friend
                        leftView.visibility = View.VISIBLE
                        rightView.visibility = View.GONE
                        Thread {
                            val str = EmojiUtil.getEmojisText(context, item.message.toString())
                            context.runOnUiThread {
                                holder.setText(R.id.tv_item_text_friend, str)
                            }

                        }.start()

                        GlideUtils.loadRadiusImg1(friendHeaderView, mFriendBean.friendHeader, 4)
                    } else {
                        //右边的 -- me
                        rightView.visibility = View.VISIBLE
                        leftView.visibility = View.GONE
                        //   holder.setText(R.id.tv_item_text_me,EmojiUtil.getEmojisText(context,item.message.toString()))
                        GlideUtils.loadRadiusImg1(meHeaderView, mUserBean.header, 4)
                        Thread {
                            val str = EmojiUtil.getEmojisText(context, item.message.toString())
                            context.runOnUiThread {
                                holder.setText(R.id.tv_item_text_me, str)
                            }

                        }.start()

                    }
                }
                CHAT_IMAGE -> {
                    val dateTimeView = holder.getView<TextView>(R.id.tv_item_datetime)
                    val leftView = holder.getView<LinearLayout>(R.id.ll_item_text_left)
                    val rightView = holder.getView<LinearLayout>(R.id.ll_item_text_right)
                    val friendHeaderView = holder.getView<ImageView>(R.id.iv_item_text_friend)
                    val meHeaderView = holder.getView<ImageView>(R.id.iv_item_text_me)
                    val imageFriend = holder.getView<ImageView>(R.id.iv_item_friend_img)
                    val imageMe = holder.getView<ImageView>(R.id.iv_item_me_img)

                    imageMe.setOnClickListener {
                        val list = ArrayList<LocalMedia>()
                        list.clear()
                        val dat = LocalMedia()
                        dat.path = item.message as String
                        list.add(dat)
                        PictureSelectorHelper().preView(list, context)
                    }

                    imageFriend.setOnClickListener {
                        val list = ArrayList<LocalMedia>()
                        list.clear()
                        val dat = LocalMedia()
                        dat.path = item.message as String
                        list.add(dat)
                        PictureSelectorHelper().preView(list, context)
                    }

                    if (holder.layoutPosition == 0) {
                        dateTimeView.visibility = View.VISIBLE

                    } else {
                        val dataFore = data[holder.layoutPosition - 1].dateTime
                        val before = DateUtils.dateToStamp2(dataFore)
                        val after = DateUtils.dateToStamp2(item.dateTime)

                        if ((after - before) > 1000 * 120) {
                            dateTimeView.visibility = View.VISIBLE
                        } else {
                            dateTimeView.visibility = View.GONE
                        }
                    }
                    dateTimeView.text = DateUtils.convertTimeToFormat(
                        DateUtils.dateToStamp2(item.dateTime),
                        item.dateTime
                    )
                    if (mUserBean.uid != item.userId) {
                        //左边的 -- friend
                        leftView.visibility = View.VISIBLE
                        rightView.visibility = View.GONE
                        GlideUtils.loadRadiusImg1(imageFriend, item.message as String, 4)
                        GlideUtils.loadRadiusImg1(friendHeaderView, mFriendBean.friendHeader, 4)
                    } else {
                        //右边的 -- me
                        rightView.visibility = View.VISIBLE
                        leftView.visibility = View.GONE
                        //   holder.setText(R.id.tv_item_text_me,EmojiUtil.getEmojisText(context,item.message.toString()))
                        GlideUtils.loadRadiusImg1(meHeaderView, mUserBean.header, 4)
                        GlideUtils.loadRadiusImg1(imageMe, item.message as String, 4)

                    }
                }
                else -> {}
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: ChatMessageBean?) {
        event?.apply {
            if ((event.type == CHAT_TEXT||event.type == CHAT_IMAGE) && event.roomType == 0) {
                //0为系统内通讯，5为语音通话
                /*     val newMessageBean = ChatMessageBean(
                         event.userId,
                         event.toUid,
                         event.type,
                         0,
                         event.message,
                         event.dateTime,
                         event.messageId,
                         event.roomId
                     )*/
                /* mList.add(event)
                 Log.e("--->", "我这")
                 mAdapter.notifyItemChanged(mList.size - 1)*/
                mAdapter.addData(event)
                mViewBinding.rvChatSingle.scrollToPosition(mAdapter.data.size - 1)

                Thread {
                    try {
                        val messageEntity = MessageEntity()
                        messageEntity.userId = event.userId
                        messageEntity.toUid = event.toUid
                        messageEntity.type = event.type
                        messageEntity.roomType = event.roomType
                        messageEntity.message = event.message.toString()
                        messageEntity.dateTime = event.dateTime ?: ""
                        messageEntity.messageId = messageId ?: ""
                        messageEntity.roomId = getRoomId(event.userId, event.toUid)
                        mMessageDao.insertMessage(messageEntity)
                    } catch (e: Exception) {
                        //可能roomId存在了
                    }
                }.start()

                sendReadAck()
            } else if (event.type == CHAT_VOICE && event.roomType == 0) {
                receiveFile(event, this@SingleChatActivity)
            }


        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

    private fun sendReadAck() {
        //发送已读ack
        WebSocketManager.instance.sendMessage(
            Gson().toJson(
                ChatMessageBean(
                    mUserId, toUid = "0",
                    type = CHAT_SYSTEM,
                    roomType = CHAT_ROOM_SINGLE,
                    CHAT_READ_ACK,
                    roomId = getRoomId(mUserId, mToUid)
                )
            )
        )
    }


    fun receiveFile(chatMessageBean: ChatMessageBean, context: Context) {
        if (chatMessageBean.type == 4) {
            val messageStreamBody = Gson().fromJson(
                chatMessageBean.message.toString(),
                MessageStreamBody::class.java
            )
            val buf = messageStreamBody.buf
            val read = messageStreamBody.read
            Log.e("--->", read.toString() + "")
            val off = messageStreamBody.off
            fileOutputStream.write(buf, 0, read)

        }
    }

}